package ch.unisi.inf.pfii.teamred.pacman.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * @author luca.vignola@lu.unisi.ch
 * 
 */
public final class HighscoreFileHandler {

	private static final String DEFAULT_FILENAME = "highscores";

	private Highscore highscore;

	public HighscoreFileHandler() {
	}

	public final void setHighscore(final Highscore highscore) {
		this.highscore = highscore;
	}

	public final Highscore getHighscore() {
		return highscore;
	}

	public final void loadHighscoreFromFile() {
		try {
			highscore = readFromFile(DEFAULT_FILENAME);
		} catch (final IOException e) {
		} catch (final ClassNotFoundException e) {
		}
	}

	public final void saveHighscoreToFile() {
		try {
			saveToFile(DEFAULT_FILENAME);
		} catch (final IOException e) {
		}
	}

	private final Highscore readFromFile(final String sourceFile)
			throws IOException, ClassNotFoundException {
		URL resource = getClass().getResource(sourceFile);
		if (resource == null) {
			throw new FileNotFoundException(sourceFile);
		}
		try {
			File source = new File(resource.toURI());
			ObjectInputStream inputStream = new ObjectInputStream(
					new FileInputStream(source));
			Highscore savedHighscore = (Highscore) inputStream.readObject();
			inputStream.close();
			return savedHighscore;
		} catch (URISyntaxException e) {
			throw new IOException("Unable to make a valid filename for "
					+ sourceFile);
		}
	}

	private final void saveToFile(final String destinationFile)
			throws IOException {
		File destination = makeAbsoluteFilename(destinationFile);
		ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(
				destination));
		os.writeObject(highscore);
		os.close();
	}

	private final File makeAbsoluteFilename(final String filename)
			throws IOException {
		try {
			File file = new File(filename);
			if (!file.isAbsolute()) {
				file = new File(getProjectFolder(), filename);
			}
			return file;
		} catch (URISyntaxException e) {
			throw new IOException("Unable to make a valid filename for "
					+ filename);
		}
	}

	private final File getProjectFolder() throws URISyntaxException {
		String myClassFile = getClass().getName() + ".class";
		URL url = getClass().getResource(myClassFile);
		return new File(url.toURI()).getParentFile();
	}
}
